<script setup>
  import {
    Management,
    Promotion,
    UserFilled,
    User,
    Crop,
    EditPen,
    SwitchButton,
    CaretBottom, Plus
  } from '@element-plus/icons-vue'
  import avatar from '@/assets/default.png'
  import {ref,reactive} from "vue";
  //条目被点击后,调用的函数
  import {useRouter} from 'vue-router'

  const router = useRouter();
  import {ElMessage, ElMessageBox} from 'element-plus'
  import {useTokenStore} from "@/store/token.js";
  import adminApi from "@/api/admin/admin.js";


  const tokenStore = useTokenStore()
  const handleCommand = (command) => {
    //判断指令
    if (command === 'logout') {
      //退出登录
      tokenStore.removeToken();
      //adminInfoStore.removeAdminInfo();
      // 跳转到登录
      router.push('/login')
    } else if (command === 'info'){
      //show dialog
      dialogForInfo.value = true
      //adminInfo里面存放了一个名字叫admin的token记得吗
      //admin.value = adminInfoStore.admin
      Object.assign(admin.value,adminInfoStore.admin)
    }else if (command === 'resetPassword'){
      dialogForPassword.value = true
      passwords.value = {}
    }
    else {
      //路由
      router.push('/admin/' + command)
    }
  }

  //查询用户信息,并放到pinia里
  import {useAdminInfoStore} from "@/store/adminInfo.js";
  const adminInfoStore = useAdminInfoStore()
  const adminIfon = () => {
    adminApi.adminIfo().then(result => {
      adminInfoStore.setAdminInfo(result.data)
    })
  }
  adminIfon()
  //修改个人信息
  const dialogForInfo = ref(false)
  const admin = ref({})

  //upload
  //function handleAvatarSuccess()是返回值函数,已经调用完后端的/upload了
  //这个应该是element的东西
  function handleAvatarSuccess(result){
    admin.value.image = result.data
  }
  const headers = ref({
    //携带token传递到后端
    Authorization: tokenStore.token
  })
  //根据什么得到admin的值呢
  const UpdateInfo = () =>{
    adminApi.update(admin.value).then(result =>{
      if (result.code === 0){
        ElMessage({message:"Congrats, this is a success message",type:"success"})
        dialogForInfo.value=false
        adminIfon()
      }//if
      else {
        ElMessage({message:"oops, it didn't work",type:"error"})
      }

    })
  }
  //修改密码
  const passwords = ref({})//存放oldPassword,newPassword and renewPassword
  const dialogForPassword = ref(false)
  //密码框的正则表达式
  const ruleFormRef = ref()
  const validatePass2 = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('Please input the password again'))
    } else if (value !== passwords.value.newPassword) {
      callback(new Error("Two inputs don't match!"))
    } else {
      callback()
    }
  }
  const rules = reactive({
    oldPassword: [
      { required: true, message: 'Please input Activity name', trigger: 'blur' },
      { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    newPassword: [
      { required: true, message: 'Please input Activity name', trigger: 'blur' },
      { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    renewPassword: [
      { required: true, message: 'Please input Activity name', trigger: 'blur' },
      { validator: validatePass2, trigger: 'blur' }
    ]
  })

  /*const changePassword = () =>{
    adminApi.resetPassword(passwords.value).then(result=>{
      if (result.code == 0){
        ElMessage.success('update success')
        dialogForPassword.value = false
      }else {
        ElMessage.error('something wrong')
      }
    })
  }*/
  const changePassword = (formEl) => {
    if (!formEl) return
    formEl.validate((valid) => {
      if (valid) {
        adminApi.resetPassword(passwords.value).then(result=>{
          if (result.code == 0){
            ElMessage.success('update success')
            dialogForPassword.value = false
          }else {
            ElMessage.error('something wrong')
          }
        })
      } else {
        console.log('error submit!')
      }
    })
  }
  //重置对话框
  const resetPasswordForm = () => {
    console.log("1111")
    Object.keys(passwords).forEach(key => {
      passwords[key] = '';
    });
  };
</script>

<template>
  <!-- element-plus中的容器 -->
  <el-container class="layout-container">
    <!-- 左侧菜单 -->
    <el-aside width="200px">
      <div class="el-aside__logo"></div>
      <!-- element-plus的菜单标签 -->
      <el-menu active-text-color="#ffd04b" background-color="#232323" text-color="#fff"
               router>
        <el-menu-item index="/admin">
          <el-icon>
            <Management/>
          </el-icon>
          <span>管理员管理</span>
        </el-menu-item>

        <el-menu-item index="/category">
          <el-icon>
            <Management/>
          </el-icon>
          <span>分类管理</span>
        </el-menu-item>

        <el-menu-item index="/product">
          <el-icon>
            <Management/>
          </el-icon>
          <span>产品管理</span>
        </el-menu-item>
<!--        <el-menu-item index="/chart">
          <el-icon>
            <Promotion/>
          </el-icon>
          <span>统计图表</span>
        </el-menu-item>-->
        <el-sub-menu>
          <template #title>
            <el-icon>
              <UserFilled/>
            </el-icon>
            <span>个人中心</span>
          </template>
          <el-menu-item index="/user/info">
            <el-icon>
              <User/>
            </el-icon>
            <span>基本资料</span>
          </el-menu-item>
          <el-menu-item index="/admin/avatar">
            <el-icon>
              <Crop/>
            </el-icon>
            <span>更换头像</span>
          </el-menu-item>
          <el-menu-item index="/user/resetPassword">
            <el-icon>
              <EditPen/>
            </el-icon>
            <span>重置密码</span>
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-aside>
    <!-- 右侧主区域 -->
    <el-container>
      <!-- 头部区域 -->
      <el-header>
        <div><strong>思途后台管理系统</strong></div>
        <!-- 下拉菜单 -->
        <!-- command: 条目被点击后会触发,在事件函数上可以声明一个参数,接收条目对应的指令 -->
        <el-dropdown placement="bottom-end" @command="handleCommand">
                    <span class="el-dropdown__box">
                        <el-avatar :src="adminInfoStore.admin.image?adminInfoStore.admin.image:avatar"/>
                        <el-icon>
                            <CaretBottom/>
                        </el-icon>
                    </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="info" :icon="User">基本资料</el-dropdown-item>
              <el-dropdown-item command="avatar" :icon="Crop">更换头像</el-dropdown-item>
              <el-dropdown-item command="resetPassword" :icon="EditPen">重置密码</el-dropdown-item>
              <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-header>
      <!-- 中间区域 -->
      <el-main>
        <!-- <div style="width: 1290px; height: 570px;border: 1px solid red;">
                    内容展示区
                </div> -->
        <router-view></router-view>
      </el-main>
      <!-- 底部区域 -->
      <el-footer>后台管理 ©2024 Created by Gao</el-footer>
    </el-container>
  </el-container>

<!-- 修改个人信息对话框 -->
  <el-dialog v-model="dialogForInfo" title="修改个人信息" width="500" :lock-scroll="false">
    <el-form :model="admin">
      <el-form-item label="名字" :label-width="60">
        <el-input v-model="admin.name" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="邮箱" :label-width="60">
        <el-input v-model="admin.email" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="手机号" :label-width="60">
        <el-input v-model="admin.phone" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="头像" :label-width="60">
        <el-upload
            class="avatar-uploader"
            action="/api/admin/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="headers"
        >
          <img v-if="admin.image" :src="admin.image" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogForInfo = false">取消</el-button>
        <el-button type="primary" @click="UpdateInfo">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
<!-- 修改密码的对话框 -->
  <el-dialog v-model="dialogForPassword" title="Change Password" width="500" @close="resetPasswordForm">
    <el-form :model="passwords" :rules="rules" ref="ruleFormRef">
      <el-form-item prop="oldPassword" label="原密码" label-width="100px">
        <el-input v-model="passwords.oldPassword" autocomplete="off" />
      </el-form-item>
      <el-form-item prop="newPassword" label="新密码" label-width="100px">
        <el-input v-model="passwords.newPassword" autocomplete="off" />
      </el-form-item>
      <el-form-item prop="renewPassword" label="确认新密码" label-width="100px">
        <el-input v-model="passwords.renewPassword" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogForPassword = false">Cancel</el-button>
        <el-button type="primary" @click="changePassword(ruleFormRef)">
          Confirm
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.layout-container {
  height: 100vh;

  .el-aside {
    background-color: #232323;

    &__logo {
      height: 120px;
      background: url('@/assets/logo.png') no-repeat center / 120px auto;
    }

    .el-menu {
      border-right: none;
    }
  }

  .el-header {
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .el-dropdown__box {
      display: flex;
      align-items: center;

      .el-icon {
        color: #999;
        margin-left: 10px;
      }

      &:active,
      &:focus {
        outline: none;
      }
    }
  }

  .el-footer {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #666;
  }
}
</style>